import React, { useCallback, useEffect } from 'react';
import doctor from '@/assets/images/avatar-doctor.svg';
import { Button, Dialog, List, Toast } from 'antd-mobile';
import NavBar from '@/components/NavBar/NavBar';
import './ConsultDetail.scss';
import { useNavigate, useParams } from 'react-router-dom';
import { useEnhanceDispatch, useEnhanceSelector } from '@/hooks';
import { cancelOrder, deleteOrder, fetchOrderDetail } from '@/store/modules/consultStore';
import { OrderType } from '@/enum';


const ConsultDetail = () => {
  const navigate = useNavigate();
  const enhanceDispatch = useEnhanceDispatch();
  const { id } = useParams();
  const orderDetail = useEnhanceSelector(state => state.consultStore.orderDetail);
  // 左边插槽内容
  const left = useCallback(() => (<span>返回</span>), []);
  // 中间插槽内容
  const children = useCallback(() => (<span>问诊详情</span>), []);

  /**
   * @description 获取订单详情的接口
   * */
  const fetchOrderInfo = async () => {
    try {
      await enhanceDispatch(fetchOrderDetail(id as string)).unwrap();
    } catch (error: any) {
      Toast.show(error.message);
    }
  };

  /**
   * @description 删除订单的回调函数
   * */
  const handleDeleteOrder = async (id: string) => {
    const confirm = await Dialog.confirm({ content: '确定删除订单?', header: '温馨提示' });
    if (!confirm) return;
    try {
      const deleteMessage = await enhanceDispatch(deleteOrder(id)).unwrap();
      Toast.show({ icon: 'success', content: deleteMessage });
    } catch (rejectedValueOrSerializedError: any) {
      Toast.show(rejectedValueOrSerializedError);
    }
  };

  /**
   * @description 取消订单的回调函数
   * */
  const handleCancelOrder = async (id: string) => {
    const confirm = await Dialog.confirm({ content: '确定取消问诊订单?', header: '温馨提示' });
    if (!confirm) return;
    try {
      const deleteMessage = await enhanceDispatch(cancelOrder(id)).unwrap();
      orderDetail.status = OrderType.ConsultCancel;
      Toast.show({ icon: 'success', content: deleteMessage });
    } catch (rejectedValueOrSerializedError: any) {
      Toast.show(rejectedValueOrSerializedError);
    }
  };

  const renderType = () => {
    if (orderDetail.type + '' === '1') {
      return '问医生';
    } else if (orderDetail.type + '' === '2') {
      return '极速问诊';
    } else if (orderDetail.type + '' === '3') {
      return '开药问诊';
    }
  };

  const renderButtonStatus = () => {
    if (orderDetail.status === OrderType.ConsultPay) {
      return (
        <>
          <Button className="gray" size="small" onClick={() => handleCancelOrder(orderDetail.id)}>取消问诊</Button>
          <Button color="primary" size="small">去支付</Button>
        </>
      );
    } else if (orderDetail.status === OrderType.ConsultWait) {
      return (
        <>
          <Button className="gray" size="small" onClick={() => handleCancelOrder(orderDetail.id)}>取消问诊</Button>
          <Button color="primary" size="small">继续沟通</Button>
        </>
      );
    } else if (orderDetail.status === OrderType.ConsultChat) {
      return (
        <>
          <Button className="gray" size="small">查看处方</Button>
          <Button color="primary" size="small">继续沟通</Button>
        </>
      );
    } else if (orderDetail.status === OrderType.ConsultComplete) {
      return (
        <>
          <Button className="gray" size="small">问诊记录</Button>
          <Button color="primary" size="small">{orderDetail.evaluateId ? '查看评价' : '去评价'}</Button>
        </>
      );
    } else if (orderDetail.status === OrderType.ConsultCancel) {
      return (
        <>
          <Button className="gray" size="small" onClick={() => handleDeleteOrder(orderDetail.id)}>删除订单</Button>
          <Button color="primary" size="small" onClick={() => navigate('/')}>咨询医生</Button>
        </>
      );
    }
  };

  const render = () => {
    if (orderDetail.id) {
      return (
        <>
          <NavBar onBack={() => navigate(-1)} back={left()} children={children()}></NavBar>
          <div className="detail-head">
            <div className="text">
              <span>{renderType()}</span>
              <span>{orderDetail.payment}元</span>
              <span className="sta green">{orderDetail.statusValue}</span>
              <p className="tip">服务医生信息</p>
            </div>
            <div className="card">
              <img className="avatar" src={doctor} alt="" />
              <p className="doc">
                <span>极速问诊</span>
                <span>{orderDetail?.docInfo?.name}</span>
              </p>
            </div>
          </div>
          <div className="detail-patient">
            <List>
              <List.Item title="患者信息" extra={`${orderDetail.patientInfo.name} | ${orderDetail.patientInfo.genderValue} | ${orderDetail.patientInfo.age}岁`}></List.Item>
              <List.Item title="患病时长" extra="一周内"></List.Item>
              <List.Item title="就诊情况" extra="未就诊过"></List.Item>
              <List.Item title="病情描述" extra={orderDetail.illnessDesc}></List.Item>
            </List>
          </div>
          <div className="detail-order">
            <h3>订单信息</h3>
            <List>
              <List.Item title="订单编号" extra={orderDetail.orderNo}></List.Item>
              <List.Item title="创建时间" extra={orderDetail.createTime}></List.Item>
              <List.Item title="应付款" extra={orderDetail.payment}></List.Item>
              <List.Item title="优惠券" extra={orderDetail.couponDeduction}></List.Item>
              <List.Item title="积分抵扣" extra={orderDetail.pointDeduction}></List.Item>
              <List.Item title="实付款" extra={orderDetail.actualPayment}></List.Item>
            </List>
          </div>
          <div className="detail-time"> 请在xxx内完成支付，超时订单将取消</div>
          <div className="detail-action van-hairline--top">
            <div className="price">
              <span className="kuang">需付款</span>
              <span className="total">￥{orderDetail.payment}</span>
            </div>
            {
              renderButtonStatus()
            }
          </div>
        </>
      );
    }
  };
  useEffect(() => {
    fetchOrderInfo();
  }, []);

  return (
    <div className="consult-detail">
      {render()}
    </div>
  );
};

export default ConsultDetail;